package yyds.sniarbtej.transformer.intellij;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import yyds.sniarbtej.transformer.BaseClassTransformer;
import yyds.sniarbtej.transformer.ClassRewriter;

public final class BlockHost extends BaseClassTransformer {
    public String canTransformClassName() {
        return "java/net/InetAddress";
    }

    public byte[] rewrite(byte[] in) {
        return transform(in, new ClassRewriter() {
            @Override
            public void rewriteMethod(MethodNode node) {
                InsnList insn;
                if ("getAllByName".equals(node.name) && "(Ljava/lang/String;Ljava/net/InetAddress;)[Ljava/net/InetAddress;".equals(node.desc)) {
                    insn = new InsnList();
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    /* blockHostByName */
                    insn.add(new MethodInsnNode(Opcodes.INVOKESTATIC, methodOverride, "C1", "(Ljava/lang/String;)Ljava/lang/String;", false));
                    insn.add(new InsnNode(Opcodes.POP));
                    node.instructions.insert(insn);
                } else if ("isReachable".equals(node.name) && "(Ljava/net/NetworkInterface;II)Z".equals(node.desc)) {
                    insn = new InsnList();
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    /* blockHostByAddress */
                    insn.add(new MethodInsnNode(Opcodes.INVOKESTATIC, methodOverride, "C1", "(Ljava/net/InetAddress;)Ljava/lang/Object;", false));
                    insn.add(new VarInsnNode(Opcodes.ASTORE, 4));
                    insn.add(new InsnNode(Opcodes.ACONST_NULL));
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 4));
                    LabelNode var2 = new LabelNode();
                    insn.add(new JumpInsnNode(Opcodes.IF_ACMPEQ, var2));
                    insn.add(new InsnNode(Opcodes.ICONST_0));
                    insn.add(new InsnNode(Opcodes.IRETURN));
                    insn.add(var2);
                    node.instructions.insert(insn);
                }
            }
        });
    }
}
